﻿using Callisto.Controls;
using StudentLive.DataModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using StudentLive.Common;
// The Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234233

namespace StudentLive.InnerPages
{
    /// <summary>
    /// A page that displays a collection of item previews.  In the Split Application this page
    /// is used to display and select one of the available groups.
    /// </summary>
    public sealed partial class OldLessonsPage : StudentLive.Common.LayoutAwarePage
    { 
        
        private Button filterRateButton, filterTypeButton;

        private SortedSet<String> filterRateStrings, filterTypeStrings;

        public OldLessonsPage()
        {
            this.InitializeComponent();

            filterRateButton = new Button();
            filterRateButton.Style = App.Current.Resources["TextPrimaryButtonStyle"] as Style;
            filterRateButton.Margin = new Thickness(5, 10, 0, 0);
            filterRateButton.Content = "Filter Rates";
            filterRateButton.FontSize = 20;
            filterRateButton.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
            filterRateButton.BorderBrush = new SolidColorBrush(Windows.UI.Colors.Transparent);
            filterRateButton.Click += FilterRateButton_Click;

            filterTypeButton = new Button();
            filterTypeButton.Style = App.Current.Resources["TextPrimaryButtonStyle"] as Style;
            filterTypeButton.Margin = new Thickness(5, 10, 0, 0);
            filterTypeButton.Content = "Filter Types";
            filterTypeButton.FontSize = 20;
            filterTypeButton.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
            filterTypeButton.BorderBrush = new SolidColorBrush(Windows.UI.Colors.Transparent);
            filterTypeButton.Click += FilterTypeButton_Click;

            //filterTypeStrings = new List<String>() { "All Files", "Word Documents", "PDF Files" };

            filterRateStrings = new SortedSet<String>() { "All Files", "5 Rated Files", "4 Rated Files", "3 Rated Files", "2 Rated Files", "1 Rated Files", "Not Rated Files" };
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]

            // TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]
            var lessonPlan = LiveDataSource.GetLessonPlan((int)navigationParameter);
            this.DataContext = lessonPlan;
            //this.DefaultViewModel["Items"] = lessonPlan.Resources;   
            try
            {
                filterTypeStrings = LiveDataSource.GetLearningResourceFileExtensionsOfLessonPlan(lessonPlan);
                filterTypeStrings.Add("All Files");
            }
            catch 
            {
                filterTypeStrings = new SortedSet<string>();
            }

        }

        private void Rating_ValueChanged(object sender, Callisto.Controls.ValueChangedEventArgs<double> e)
        {
            if (Object.Equals(e.NewValue, e.OldValue)) return;
            ResourceItem resource = (ResourceItem)((Control)sender).DataContext;
            resource.Rate = e.NewValue;
            LiveDataSource.UpdateLearningResource(resource);
        }

        private void TypeButton_Click(object sender, RoutedEventArgs e)
        {
            DoSortWithType();

            if (FilterPanelType.Visibility == Windows.UI.Xaml.Visibility.Visible)
            {
                return;
            }
            FilterPanelType.Visibility = Windows.UI.Xaml.Visibility.Visible;
            FilterPanelType.Children.Add(filterTypeButton);

            FilterPanelRate.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            FilterPanelRate.Children.Clear();

        }

        private void RateButton_Click(object sender, RoutedEventArgs e)
        {
            DoSortWithRate();

            if (FilterPanelRate.Visibility == Windows.UI.Xaml.Visibility.Visible)
            {
                return;
            }
            FilterPanelRate.Visibility = Windows.UI.Xaml.Visibility.Visible;
            FilterPanelRate.Children.Add(filterRateButton);

            FilterPanelType.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            FilterPanelType.Children.Clear();

        }

        private void Favorite_Click_1(object sender, RoutedEventArgs e)
        {
            var lr = ((ResourceItem)((Button)sender).Tag);
            lr.IsFavoured = !lr.IsFavoured;
            
            LiveDataSource.UpdateLearningResource(lr);
        }

        async void DefaultLaunch(string path)
        {
            // Path to the file in the app package to launch

            var file = await StorageFile.GetFileFromPathAsync(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, path));

            if (file != null)
            {
                // Set the option to show the picker
                //var options = new Windows.System.LauncherOptions();
                //options.DisplayApplicationPicker = true;

                // Launch the retrieved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(file);
                if (success)
                {
                    // File launched
                }
                else
                {
                    // File launch failed
                }
            }
            else
            {
                // Could not find file
            }
        }

        private void itemDetailTitlePanel_ItemClick(object sender, ItemClickEventArgs e)
        {
            ResourceItem learningResource = (ResourceItem)e.ClickedItem;
            if (learningResource.IsDownloaded)
            {
                DefaultLaunch(learningResource.Description);
            }
        }

        private async void DownloadButton_Click_1(object sender, RoutedEventArgs e)
        {
            if (((sender as Button).Content as string) == "Download")
            {
                (sender as Button).Content = "Cancel";
                StackPanel panel = (sender as Button).Parent as StackPanel;
                startLoadingWithParent(panel);
                await LiveDataSource.DownloadResource((ResourceItem)((Button)sender).Tag);
                stopLoadingWithParent(panel);
            }
            else
            {
                // TODO: cancel the download,,,
            }
        }

        void startLoadingWithParent(StackPanel parent)
        {
            ProgressBar bar = new ProgressBar();
            bar.IsIndeterminate = true;
            bar.Margin = new Thickness(0, 10, 0, 0);
            bar.Width = parent.Width;
            parent.Children.Insert(2, bar);
        }

        void stopLoadingWithParent(StackPanel parent)
        {
            foreach (var item in parent.Children)
            {
                if ((item as ProgressBar) != null)
                {
                    parent.Children.Remove(item);
                }
            }
        }

        void DoSortWithType()
        {
            LessonPlanItem lessonPlan = this.DataContext as LessonPlanItem;

            lessonPlan.ResourcesMirror = LiveDataSource.SortResourcesByType(lessonPlan.ResourcesMirror);
        }

        void DoSortWithRate()
        {
            LessonPlanItem lessonPlan = this.DataContext as LessonPlanItem;

            lessonPlan.ResourcesMirror = LiveDataSource.SortResourcesByRate(lessonPlan.ResourcesMirror);
        }

        void CreateMenuWithTargetAndItems(object sender, SortedSet<string> items, string TAG)
        {
            Flyout f = new Flyout();

            f.Placement = PlacementMode.Bottom;
            f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)

            Menu menu = new Menu();

            foreach (var item in items)
            {
                MenuItem menuItem = new MenuItem();
                menuItem.Text = item;
                menuItem.Tag = TAG;

                menuItem.Tapped += FlyoutMenuItem_Tapped;
                menu.Items.Add(menuItem);
            }

            f.Content = menu;

            f.IsOpen = true;
        }

        private void FlyoutMenuItem_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if ((sender as MenuItem).Tag as string == "RATING_ITEM")
            {
                FilterFilesWithRate((sender as MenuItem).Text);
            }
            else if ((sender as MenuItem).Tag as string == "TYPE_ITEM")
            {
                FilterFilesWithType((sender as MenuItem).Text);
            }
        }

        private void FilterFilesWithType(string selectedType)
        {
            LessonPlanItem lessonPlan = this.DataContext as LessonPlanItem;

            if (selectedType == "All Files")
            {
                lessonPlan.ResourcesMirror = lessonPlan.Resources.OrderBy<ResourceItem, string>(lr => lr.Name.Split('.').Last());
            }
            else
            {
                lessonPlan.ResourcesMirror = lessonPlan.Resources.Where<ResourceItem>(r => r.Name.EndsWith(selectedType, StringComparison.OrdinalIgnoreCase)).OrderBy(lr => lr.DatabaseItem.LearningResourceGUID);
            }
        }
        
        private void FilterFilesWithRate(string selectedRate)
        {
            LessonPlanItem lessonPlan = this.DataContext as LessonPlanItem;

            if (selectedRate == "All Files")
            {
                lessonPlan.ResourcesMirror = lessonPlan.Resources.OrderBy<ResourceItem, double>(lr => lr.Rate);
            }
            else
            {
                double rate = 0;
                string temp = selectedRate.Split(' ').ElementAt(0);

                if (temp != "Not")
                {
                    rate = Double.Parse(temp);
                }
                lessonPlan.ResourcesMirror = lessonPlan.Resources.Where<ResourceItem>(lr => lr.Rate == rate).OrderBy(lr => lr.DatabaseItem.LearningResourceGUID);
            }
        }
     
        private void FilterTypeButton_Click(object sender, RoutedEventArgs e)
        {
            CreateMenuWithTargetAndItems(sender, filterTypeStrings, "TYPE_ITEM");
        }

        private void FilterRateButton_Click(object sender, RoutedEventArgs e)
        {
            CreateMenuWithTargetAndItems(sender, filterRateStrings, "RATING_ITEM");
        }

      
    }
}
